package com.vast.vastlcd.connection;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.vast.vastlcd.lcdAPI.LCDAPICore;
import com.vast.vastlcd.lcdAPI.LCDMessageHeader;
import com.vast.vastlcd.views.ImageView;

public class LCDPipeConnection implements IConnection {

	private String pipeFileName;
	private boolean createPipe;
	private FileInputStream pipeFile = null;
	private byte[] msgHdrBuffer = new byte[LCDMessageHeader.LCD_MSG_HDR_BYTE_SIZE];	
	
	public LCDPipeConnection(String pipeFileName, boolean createPipe) {
		this.createPipe = createPipe;
		this.pipeFileName = pipeFileName;
	}
	
	@Override
	public boolean connect() {
		//ImageView.setImage(null);
		if (createPipe) {
			LCDAPICore.LcdPipeOpenConnect(pipeFileName);
		}
			
		try {
			pipeFile = new FileInputStream(pipeFileName);
		} catch (FileNotFoundException e1) {
			return false;
		}			
		if (pipeFile == null)
			return false;

		return true;
	}

	@Override
	public boolean initialize() {
		return true;
	}

	@Override
	public boolean synchonize() {
		int bytesRead = 0;
		try {
			bytesRead = pipeFile.read(msgHdrBuffer);									
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		if (bytesRead == -1)
			return false;
				
		LCDMessageHeader msgHeader = LCDMessageHeader.nativeToJava(msgHdrBuffer);
		
		if (msgHeader.nMessageLength > 0) {
			byte[] msgBodyBuffer = new byte[msgHeader.nMessageLength];
			try {
				pipeFile.read(msgBodyBuffer);
			} catch (IOException e) {
				e.printStackTrace();
			}				
			msgHeader.ProcessMessageHeader(msgBodyBuffer);		
		}
		return true;
	}

	public String getPipeFileName() {
		return pipeFileName;
	}

	public void setPipeFileName(String pipeFileName) {
		this.pipeFileName = pipeFileName;
	}

	public void setCreatePipe(boolean createPipe) {
		this.createPipe = createPipe;
	}

}
